package zcommon

import (
	"bufio"
	"io"
	"os"
)

// 文件逐行处理
func FileEachLine(filePath string, cb func(line string) error) error {
	f, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	for {
		if !scanner.Scan() {
			break
		}

		line := scanner.Text()
		if cb != nil {
			if err := cb(line); err != nil {
				return err
			}
		}
	}

	return nil
}

// 复制文件
func CopyFile(srcName, dstName string) (written int64, err error) {
	src, err := os.Open(srcName)
	if err != nil {
		return
	}
	defer src.Close()

	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return
	}
	defer dst.Close()

	return io.Copy(dst, src)
}
